<template>
    <!-- 支出管理 相关图标统计 -->
    <div class="ChartsExpenditure">
        <el-card class="box-card stat-box" shadow="never" style="margin-bottom: 20px;">
            <el-row :gutter="20">
                <TheElCol v-if="false">
                    <ul class="box-wrapper">
                        <li class="box-item dark-title">
                            <div class="cell">
                                <span>类目</span>
                            </div>
                            <div class="cell">
                                <span>值</span>
                            </div>
                        </li>
                        <li class="box-item">
                            <div class="cell">
                                <span>账户余额</span>
                            </div>
                            <div class="cell">
                                <span>
                                    <i>￥</i>
                                    {{ total.income }}
                                </span>
                            </div>
                        </li>
                        <li class="box-item">
                            <div class="cell">
                                <span>总负债</span>
                            </div>
                            <div class="cell">
                                <span>
                                    <i>￥</i>
                                    {{ total.expenditure }}
                                </span>
                            </div>
                        </li>
                        <li class="box-item">
                            <div class="cell">
                                <span>月平均收入/支出</span>
                            </div>
                            <div class="cell">
                                <span>￥ 15000 / 1000</span>
                            </div>
                        </li>
                        <li class="box-item">
                            <div class="cell">
                                <span>负债率</span>
                            </div>
                            <div class="cell">
                                <span>100%</span>
                            </div>
                        </li>
                        <!-- <li class="box-item">
                            <div class="cell">
                                <span>有风险流动资金</span>
                            </div>
                            <div class="cell">
                                <span>￥ 15000</span>
                            </div>
                        </li>-->
                        <li class="box-item">
                            <div class="cell">
                                <span>风险指数</span>
                            </div>
                            <div class="cell">
                                <span>100%</span>
                            </div>
                        </li>
                    </ul>
                </TheElCol>
                <TheElCol>
                    <ChartsLine
                        title="最近60日每日支出趋势图"
                        :style="{height: height, width: '100%'}"
                        :dataSource="dataSource"
                    ></ChartsLine>
                </TheElCol>
                <TheElCol>
                    <div class="ranking-wrap">
                        <div class="ranking-title">最近半年支出排行榜</div>
                        <ul class="ranking-list">
                            <template v-if="rankings.length !== 0">
                                <li v-for="(item, index) in rankings" :key="index" class="ranking-item">
                                    <div class="ranking-left">
                                        <div class="ranking-title">{{ item.fromName }}</div>
                                        <div class="ranking-datetime">{{ item.fromTime }}</div>
                                    </div>
                                    <div class="ranking-right">
                                        <span>
                                            <i>￥</i>
                                            {{ item.fromMoney }}
                                        </span>
                                    </div>
                                </li>
                            </template>

                            <template v-else>
                                <li class="ranking-item" style="border: 0">暂无数据</li>
                            </template>
                        </ul>
                    </div>
                </TheElCol>
                <TheElCol>
                    <div class="ranking-wrap">
                        <div class="ranking-title">最近半年收入排行榜</div>
                        <ul class="ranking-list">
                            <template v-if="rankingsCome.length !== 0">
                                <li v-for="(item, index) in rankingsCome" :key="index" class="ranking-item">
                                    <div class="ranking-left">
                                        <div class="ranking-title">{{ item.toName }}</div>
                                        <div class="ranking-datetime">{{ item.toTime }}</div>
                                    </div>
                                    <div class="ranking-right">
                                        <span>
                                            <i>￥</i>
                                            {{ item.toMoney }}
                                        </span>
                                    </div>
                                </li>
                            </template>
                            <template v-else>
                                <li class="ranking-item" style="border: 0">暂无数据</li>
                            </template>
                        </ul>
                    </div>
                </TheElCol>
            </el-row>
        </el-card>
    </div>
</template>
<script>
import ChartsLine from '@/components/Charts/Line';
import {getChartsExpenditureMonthLast, getChartsExpenditureRanking} from '@/api/home';
import moment from 'moment';
import {keep2decimalPlaces} from '@/filters';
import {BASIC_MONEY, THE_MOMENT_YYYYMMDD_HHMMSS} from '@/utils/constant';
// import FullScreen from '@/components/FullScreen/index';
import variables from '@/styles/variables.scss';

const colorPrimary = variables.colorPrimary;

export default {
    name: 'ChartsExpenditure',
    props: {
        resizeRandomId: {
            type: String
        },
        height: {
            type: String,
            default: '200px'
        }
    },
    components: {
        ChartsLine
        // FullScreen
    },
    data() {
        return {
            isUpdateChartsResize: `acb${Math.random()}`,
            dataSource: {},
            total: {
                income: '100000.00',
                expenditure: '100000.29'
            },
            // 支出排行榜
            rankings: [],
            // 收入排行榜
            rankingsCome: [],
            isFullScreen: false,
            theTimeoutId: null
        };
    },
    computed: {
        isWeixin() {
            return this.$store.getters['app/isWeixin'];
        }
    },
    watch: {
        resizeRandomId(val) {
            this.isUpdateChartsResize = val;
        },
        isFullScreen(val) {
            clearTimeout(this.theTimeoutId);
            this.theTimeoutId = setTimeout(() => {
                this.isUpdateChartsResize = `acb${Math.random()}`;
            }, 10);
        }
    },
    created() {
        this.handleGetData();
    },
    methods: {
        handleGetData() {
            this.getChartsExpenditureRanking();

            this.getChartsExpenditureMonthLast();
        },
        async getChartsExpenditureRanking() {
            try {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);

                const params = {
                    pageSize: 3,
                    page: 1,
                    startTime: moment(start).format(THE_MOMENT_YYYYMMDD_HHMMSS),
                    endTime: moment(end).format(THE_MOMENT_YYYYMMDD_HHMMSS)
                };

                const result = await getChartsExpenditureRanking(params);
                const {data: res} = result;
                if (res.status === 200) {
                    const {data, comeData} = res;
                    this.rankings = data.map(i => {
                        return {
                            fromName: i.fromName,
                            fromMoney: keep2decimalPlaces(i.fromMoney / BASIC_MONEY),
                            fromTime: moment(i.fromTime).format('MM-DD HH:mm')
                        };
                    });
                    this.rankingsCome = comeData.map(i => {
                        return {
                            toName: i.toName,
                            toMoney: keep2decimalPlaces(i.toMoney / BASIC_MONEY),
                            toTime: moment(i.toTime).format('MM-DD HH:mm')
                        };
                    });
                } else {
                    throw result;
                }
            } catch (error) {
                console.error(error);
            }
        },

        async getChartsExpenditureMonthLast() {
            try {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);

                // 生成月份数据
                const months = [];
                let values = [];
                // for (let num = 29; num >= 0; num--) {
                for (let num = 29; num >= -30; num--) {
                    const current = end.getTime() - num * 3600 * 1000 * 24;
                    const today = moment(current).format('YYYY-MM-DD');
                    months.push(today);
                    // values.push(0);
                }

                const params = {
                    startTime: moment(start).format(THE_MOMENT_YYYYMMDD_HHMMSS),
                    endTime: moment(end).format(THE_MOMENT_YYYYMMDD_HHMMSS)
                };

                const result = await getChartsExpenditureMonthLast(params);
                const {data: res} = result;

                // 接口返回的数据
                const list = res.data;
                // 用于标识 开始、结束 计算折线图 因为数据有可能空缺 在后端返回的数据范围中 空缺部分为值0
                let isCount = false;
                let isCountEndIndex = 0;
                values = months.map((today, index) => {
                    if (list.length > 0 && list[0].date === today) {
                        isCount = true;
                    }
                    if (list.length > 0 && list[list.length - 1].date === today) {
                        isCount = false;
                        isCountEndIndex = index;
                    }

                    const defaultObj = {date: today};

                    if (isCount) {
                        defaultObj.value = 0;
                    } else if (!isCount && index > isCountEndIndex) {
                        defaultObj.value = '';
                    }
                    // 根据日期返回的数据
                    const item = list.find(i => i.date === today) || defaultObj;

                    return {
                        ...item,
                        value: item.value !== 0 && !item.value ? '' : keep2decimalPlaces(item.value / BASIC_MONEY)
                    };
                });

                const listAverage = list.length
                    ? list.reduce((t, i) => t + i.value, 0) / (list.length * BASIC_MONEY) // eslint-disable-line
                    : 0;
                // 平均值线
                const markLineData = listAverage ? [{yAxis: listAverage, name: `平均值${listAverage.toFixed(2)}`}] : [];

                // 标识一下今天markPoint
                const today = moment(new Date()).format('YYYY-MM-DD');
                const todaytime = moment(today).valueOf();
                const yAxis = (values.find(i => i.date === today) || {}).value;
                const markPointToday = {
                    xAxis: todaytime + '',
                    yAxis,
                    name: `${moment(today).format('MM-DD')} ${yAxis ? `￥${yAxis}` : '暂无数据'}`
                };

                const option = {
                    title: {
                        text: '最近60日每日支出趋势图',
                        left: 'left',
                        // padding: [0, 0, 0, 0],
                        textStyle: {
                            fontWeight: 'normal',
                            fontSize: 14
                        }
                    },
                    tooltip: {
                        trigger: 'axis',
                        // formatter: '{b0}<br /> {c0}',
                        // formatter: '{b0}<br /> {c0}',
                        formatter: function(params) {
                            const [{name, value}] = params;
                            return `${moment(name - 0).format('YYYY-MM-DD')}<br>${value ? `￥${value}` : '暂无数据'}`;
                        },
                        axisPointer: {
                            type: 'cross',
                            label: {
                                // backgroundColor: '#6a7985'
                                backgroundColor: 'rgba(106,121,133,.6)'
                            }
                        }
                    },
                    yAxis: {
                        type: 'value'
                    },
                    xAxis: {
                        // 把时间格式转换为 时间戳
                        data: months.map(i => moment(i).valueOf()),
                        type: 'category',
                        axisLabel: {
                            formatter: function(value, index) {
                                // return index === 0 ?
                                //  moment(value).format('YYYY-MM-DD') : moment(value).format('MM-DD');
                                return moment(value - 0).format('MM-DD');
                            }
                        },
                        axisPointer: {
                            label: {
                                backgroundColor: 'rgba(106,121,133,.5)',
                                // backgroundColor: 'transparent',
                                formatter: function(params) {
                                    return moment(params.value - 0).format('YYYY-MM-DD');
                                }
                            }
                        }
                    },
                    series: [
                        {
                            type: 'line',
                            symbol: 'emptyCircle', // 标记图形
                            symbolSize: 4, // 标记的大小 默认值为4
                            data: values,
                            lineStyle: {
                                width: 2 // 线的宽度 默认为2
                            },
                            silent: true, // 取消点击事件
                            color: [colorPrimary], // 颜色
                            markPoint: {
                                show: true,
                                symbol: 'pin', // 标记(气泡)的图形
                                symbolSize: 1, // 标记(气泡)的大小
                                label: {
                                    align: 'left',
                                    position: 'top',
                                    distance: 5,
                                    // color: colorPrimary,
                                    color: 'green',
                                    formatter: '{b}' // b为 data: [{xAxis: '2020-04-17'}] 中的name值
                                },
                                itemStyle: {
                                    color: 'rgba(0, 0, 0, 0.2)'
                                },
                                // data: [{name: '04-17', value: 30, xAxis: '2020-04-17', yAxis: 30}]
                                // data: [{type: 'max', name: '今天'}]
                                data: [
                                    // {xAxis: '2020-04-17', yAxis: '30.00', name: '04-17 30.00'},
                                    markPointToday
                                    // ,
                                    // {
                                    //     type: 'max',
                                    //     name: `最大值 ￥${keep2decimalPlaces(
                                    //         Math.max(...values.map(i => i.value - 0))
                                    //     )}`
                                    // }
                                ]
                            },
                            markLine: {
                                symbol: ['circle', 'arrow'], // 标记(气泡)的图形
                                symbolSize: 2, // 标记(气泡)的大小
                                lineStyle: {
                                    width: 1,
                                    color: 'green'
                                },
                                label: {
                                    // distance: 2,
                                    distance: -76,
                                    position: 'start', // start end middle
                                    color: 'green',
                                    formatter: '{b}' // b为 data: [{xAxis: '2020-04-17'}] 中的name值
                                },
                                data: markLineData
                            }
                        }
                    ]
                };
                // this.dataSource = [months, values];
                this.dataSource = option;
            } catch (error) {
                console.error(error);
            }
        }
    }
};
</script>
<style lang="scss" scoped>
@import './ranking.scss';
.stat-box {
    ::v-deep {
        .el-card__body {
            height: inherit;
        }
    }
    .box-wrapper {
        height: inherit;
        display: flex;
        flex-direction: column;
        // justify-content: center;
        padding: 5px 15px;
        box-sizing: border-box;
        .box-item {
            display: flex;
            border-bottom: 1px solid $--color-border-normal;
            .cell {
                flex: 1;
                box-sizing: border-box;
                padding: 10px 0;
                text-align: left;
                font-size: $--font-size-14;
                &:first-child {
                    color: $--color-text-title;
                }
                &:last-child {
                    color: $--color-text-title;
                }
            }
        }
        .box-item.dark-title {
            .cell {
                span {
                    color: $--color-text-sub;
                }
            }
        }
    }
}

.head-total-wrap {
    display: flex;
    flex-flow: row nowrap;
    padding: 15px 0;

    & > li {
        flex: 1;
        text-align: center;
        box-sizing: border-box;
        &:first-child {
            border-right: 1px solid $--color-border-normal;
        }
        .cell {
            display: inline-block;
            & > span {
                display: block;
            }
            & > span:first-child {
                font-size: $--font-size-14;
                text-align: left;
                margin-bottom: 8px;
            }
            & > span:last-child {
                i {
                    font-size: $--font-size-14;
                }
                font-size: $--font-size-18;
            }
        }
    }
}
</style>
